package com.example.back.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.example.back.dto.req.ChangePasswordReq;
import com.example.back.jpa.AdminRepository;
import com.example.back.service.ChangePasswordService;
import com.example.back.utils.UserUtils;
import com.example.common.entity.Admin;
import com.example.common.support.ApiException;
import com.example.common.utils.CheckUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.javers.spring.annotation.JaversAuditable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 修改密码
 */
@Service
public class ChangePasswordServiceImpl implements ChangePasswordService {
    @Resource
    private AdminRepository adminRepository;

    @Resource
    private UserUtils userUtils;

    /**
     *修改密码信息
     */
    @Override
    @JaversAuditable
    public Object saveChange(ChangePasswordReq req) {

        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));

        if(ObjectUtils.isEmpty(req.getOldpwd() )|| ObjectUtils.isEmpty(req.getOldpwd())){
            throw  new ApiException(1,"新密码和旧密码不能为空");
        }

        if(req.getOldpwd() == req.getNewpwd()){
            throw  new ApiException(1,"新密码和旧密码不能相同");
        }

        Admin objs = adminRepository.findById(userUtils.getUser().getId()).orElse(null);

        if(!objs.getPassword().equals(DigestUtil.md5Hex(req.getOldpwd()))){
            throw  new ApiException(1,"当前密码错误，修改失败");
        }

        objs.setPassword(DigestUtil.md5Hex(req.getNewpwd()));
        Date date = DateUtil.date();
        DateTime newDate = DateUtil.offsetMonth(date, 3);
        objs.setEditTime(newDate);

        adminRepository.save(objs);
        return null;
    }
}
